<?php

namespace App\Http\Controllers;

use App\Models\UserWallet;
use App\Models\WechatUser;
use App\Models\Withdraw;
use Illuminate\Http\Request;

class WithdrawController extends Controller
{
    public function getConfig()
    {
        $array = get_withdraw_option();
        return response()->json($array);
    }
    public function getWithdrawList()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $userId = request()->input('user_id', 0);
        $list = Withdraw::where([['user_id', $userId], ['status', '>', 0]])
            ->orderBy('created_at', 'desc')
            ->paginate($pn);
        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);

    }

    public function getWithdrawTime()
    {
        $userId = request()->input('user_id', 0);
        $withdrawTime = Withdraw::where([['user_id', $userId], ['status', '>', 0]])->count();
        return response()->json([
            'recode' => 1,
            'withdraw_time' => $withdrawTime,
        ]);

    }

    public function apply()
    {
        $userId = request()->input('user_id', 0);
        $money = request()->input('money', 0);
        $tele = request()->input('tele', '');

        $array = get_withdraw_option();
        if ($array['min'] > $money) {
            $min = $array['min'] / 100;
            return response()->json(['recode' => 0, 'msg' => '最低提现金额为' . $min . '元']);
        }

        $user = WechatUser::find($userId);
        if (!$user) {
            return response()->json(['recode' => 0, 'msg' => '没有找到用户']);
        }

        $userWallet = UserWallet::where('user_id', $userId)->first();

        if (!($userWallet && $userWallet->money >= $money)) {
            return response()->json(['recode' => 0, 'msg' => '您的红包余额小于您提现金额']);
        }

        $withdraw = new Withdraw;
        $withdraw->user_id = $userId;
        $withdraw->money = $money;
        $withdraw->tele = $tele;

        $userWallet->money = $userWallet->money - $money;
        $userWallet->withdraw_time = $userWallet->withdraw_time + 1;

        \DB::transaction(function () use ($userWallet, $withdraw) {
            $withdraw->save();
            $userWallet->save();
        });
        return response()->json(['recode' => 1, 'msg' => '提现成功，请等待客服处理']);
    }
}
